from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from django.utils import translation
from d115.mixins import AuditMixin, PositionMixin
import textwrap

class Questionnaire(models.Model):
    language = models.CharField(max_length=2, choices=settings.LANGUAGES, verbose_name=_("Language"), default=settings.LANGUAGE_CODE)
    name = models.CharField(max_length=1024, blank=True, null=True, verbose_name=_("Poll name"))
    code_name = models.CharField(max_length=256, blank=True, null=True, verbose_name=_("Code name (one word)"))
    is_active = models.BooleanField(default=True, verbose_name=_("Is active?"))

    class Meta:
        verbose_name = _("poll")
        verbose_name_plural = _("polls")

    def __unicode__(self):
        return u"%s" % self.name

class Question(PositionMixin):
    questionnaire = models.ForeignKey(Questionnaire, related_name="questions", verbose_name=_("Questionnaire"))
    question = models.TextField(verbose_name=_("Question"))
    qtype = models.CharField(max_length=20, choices=(("text", _("Open-ended question")), ("quiz", _("Multiple-choice question (one answer allowed)")), ("quiz2", _("Multiple-choice question (several answers allowed)")), ("bool", _("Yes or No question"))), verbose_name=_("Question type"), default="text")
    is_active = models.BooleanField(default=True, verbose_name=_("Is active?"))

    class Meta(PositionMixin.Meta):
        verbose_name = _("poll question")
        verbose_name_plural = _("poll questions")

    def __unicode__(self):
        return u"%s" % self.question

    def positive_answers(self):
        if self.qtype == "bool":
            return self.answers.filter(answer="yes").count()
        return None

    def negative_answers(self):
        if self.qtype == "bool":
            return self.answers.filter(answer="no").count()
        return None

class QuestionOption(models.Model):
    question = models.ForeignKey(Question, verbose_name=_("Question"), related_name="options")
    label = models.TextField(verbose_name=_("Label"))
    value = models.CharField(max_length=255, verbose_name=_("Value"))
    comments = models.BooleanField(default=False)

    def __unicode__(self):
        return u"%s" % self.label

    class Meta:
        verbose_name = _("question option")
        verbose_name_plural = _("question options")

    def answer_count(self):
        return self.question.answers.filter(answer=self.value).count()

class AnswerSet(AuditMixin):
    full_name = models.CharField(max_length=512, blank=True, null=True, verbose_name=_("Full name"))
    city = models.CharField(max_length=1024, blank=True, null=True, verbose_name=_("City"))
    email = models.CharField(max_length=1024, blank=True, null=True, verbose_name=_("E-mail"))
    phone = models.CharField(max_length=255, blank=True, null=True, verbose_name=_("Phone"))
    poll = models.ForeignKey(Questionnaire, blank=True, null=True, verbose_name=_("Questionnaire"))

    def for_print(self):
        return mark_safe("<a href='/polls/answerset/%d/' target='_blank'>/polls/answerset/%d/</a>" % (self.id, self.id))
    for_print.allow_tags = True

    class Meta(AuditMixin.Meta):
        verbose_name = _("answer set")
        verbose_name_plural = _("answer sets")

    def __unicode__(self):
        return u"%s" % (self.full_name or self.created_by or self.created)

class Answer(models.Model):
    answer_set = models.ForeignKey(AnswerSet, related_name="answers", verbose_name=_("Answer set"))
    question = models.ForeignKey(Question, related_name="answers", verbose_name=_("Question"))
    answer = models.TextField(blank=True, null=True, verbose_name=_("Answer"))

    def question_display(self):
        return mark_safe('<br />\n'.join(textwrap.wrap(self.question.question, 60)))
    question_display.allw_tags = True
    question_display.verbose_name = _("Question")

    def decoded_answer(self):
        ans = self.answer
        if self.question.qtype == 'quiz':
            if ans:
                if '|' in self.answer:
                    (acode, comment) = self.answer.split('|',1)
                else:
                    acode = self.answer
                    comment = None
                if acode:
                    qo = QuestionOption.objects.filter(question=self.question, value=acode)
                    if qo.count():
                        ans = qo[0].label
                        if comment:
                            ans = unicode(ans) + u' [%s]' % comment
        elif self.question.qtype == 'bool':
            ans = _('Yes') if self.answer=='1' else _('No')
        elif self.question.qtype == 'quiz2':
            ans = []
            if self.answer:
                answers = self.answer.split('%$%')
                for a in answers:
                    if '|' in a:
                        (acode, comment) = a('|',1)
                    else:
                        acode = a
                        comment = None
                    if acode:
                        qo = QuestionOption.objects.filter(question=self.question, value=acode)
                        if qo.count():
                            new_ans = qo[0].label
                            if comment:
                                new_ans = unicode(new_ans) + u' [%s]' % comment
                        else:
                            new_ans = acode
                        ans.append(new_ans)
            ans = '\n\n'.join(ans)
        return unicode(ans)
    decoded_answer.verbose_name = _("Answer")

    class Meta:
        verbose_name = _("answer")
        verbose_name_plural = _("answers")
        ordering = ["question__position", ]
